package edu.jmu.service.user.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import edu.jmu.bean.QueryResult;
import edu.jmu.bean.user.Depart;
import edu.jmu.bean.user.User;
import edu.jmu.service.base.DaoSupport;
import edu.jmu.service.user.UserService;
/**
 * 用户业务类 
 * @author Neal
 *
 */
@Service
public class UserServiceBean extends DaoSupport<User> implements UserService{

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public boolean checkUser(User user) {
		String jpql = "select count(o) from User o where o.userName = ?1 and o.passWord = ?2";
		Long count = (Long) em.createQuery(jpql).setParameter(1, user.getUserName()).setParameter(2, user.getPassWord())
				.getSingleResult();		
		return count>0;
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public QueryResult<User> getUserByconfition(Depart depart,User user)
	{
		QueryResult<User> users = null;
		String jpql = "";
		boolean userBool = (user != null  && (!"".equals(user.getUserName())));
		boolean departBool = (depart != null && (!"".equals(depart.getId())));
		boolean branchBool = (depart.getBranch() != null && (!"".equals(depart.getBranch().getId())));
		if(branchBool){       //机构不空
			if(departBool){    //部门不空
				jpql = "select o from User o where o.depart.branch = ?1 and o.depart.id = ?2";
				users = (QueryResult<User>)em.createQuery(jpql).setParameter(1, depart.getBranch().getId()).setParameter(2, depart.getId()).getResultList();
			} else{   //机构不空，其它都空
				jpql = "o.depart.branch = ?1 )";
				users = super.getScrollData(0, Integer.MAX_VALUE, jpql, new Depart[]{depart});
			}
		}
		else{
			if(userBool){  //用户不空，其它都空
				jpql = "o.userName = ?1";
				users = super.getScrollData(0, Integer.MAX_VALUE, jpql, new User[]{user});
			}
		}
		return users;
	}

}
